<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container">
      <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item" placeholder="订单号"
                v-model="listQuery.idsStr">
      </el-input>
      <el-select readonly @keyup.enter.native="handleFilter" @focus="handleDept()" style="width: 200px;"
                 class="filter-item" v-model="listQuery.distributeBy" placeholder="配送员">
        <el-option
          v-for="item in userList"
          :key="item.userId"
          :label="item.username"
          :value="item.username">
        </el-option>
      </el-select>
      <el-select @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item"
                 v-model="listQuery.orderStatus" placeholder="订单状态">
        <el-option
          v-for="item in orderStatusOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value">
        </el-option>
      </el-select>
      <el-date-picker
        @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item"
        v-model="listQuery.gmtOrderStart"
        type="date"
        placeholder="开始时间" format="yyyy 年 MM 月 dd 日"
        value-format="yyyy-MM-dd hh:mm:ss">
      </el-date-picker>
      <el-date-picker
        @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item"
        v-model="listQuery.gmtOrderEnd"
        type="date"
        placeholder="结束时间" format="yyyy 年 MM 月 dd 日"
        value-format="yyyy-MM-dd hh:mm:ss">
      </el-date-picker>
      <el-button class="filter-item" type="primary" v-waves icon="search" @click="handleFilter">搜索</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" @click="handleCreate" type="primary" icon="edit"
                 v-if="roleManager_btn_add">添加
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" @click="getToken" type="primary" icon="edit"
                 v-if="roleManager_btn_add">批量导入
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" @click="handleDistribute" type="primary" icon="edit"
                 v-if="roleManager_btn_add">批量分配
      </el-button>

      <el-button class="filter-item" style="margin-left: 10px;" @click="handleGathering" type="primary" icon="edit"
                 v-if="roleManager_btn_add">批量收款
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" @click="handleScaner" type="primary" icon="edit"
                 v-if="roleManager_btn_add">扫码枪录入
      </el-button>
      <OSSUpload v-on:onFileSelected="addIdCard" v-bind:imgList="imageList0"/>
    </div>


    <el-table :key='tableKey' :data="list" v-loading="listLoading" @selection-change="handleSelectionChange"
              element-loading-text="给我一点时间" border fit highlight-current-row style="width: 99%">
      <el-table-column
        type="selection"
        width="55">
      </el-table-column>
      <el-table-column align="center" label="序号">
        <template slot-scope="scope">
          <span>{{scope.row.id}}</span>
        </template>
      </el-table-column>

      <el-table-column label="订单号">
        <template slot-scope="scope">
          <span>{{scope.row.orderId}}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="应收金额">
        <template slot-scope="scope">
          <span>{{scope.row.orderMoney}}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="收货地址">
        <template slot-scope="scope">
          <span>{{scope.row.orderAddress }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="状态">
        <template slot-scope="scope">
          <span>{{scope.row.orderStatus }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="创建时间">
        <template slot-scope="scope">
          <span>{{scope.row.gmtOrder | parseTime('{y}-{m}-{d} {h}:{i}')}}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="220">
        <template slot-scope="scope">
          <el-button size="mini" type="success" v-if="roleManager_btn_edit" @click="handleUpdate(scope.row)">编辑
          </el-button>
          <el-button size="mini" type="danger" v-if="roleManager_btn_del" @click="handleDelete(scope.row)">删除
          </el-button>
          <el-button size="mini" type="info" plain @click="handlePermission(scope.row)" v-if="roleManager_btn_perm">权限
          </el-button>
        </template>
      </el-table-column>

    </el-table>

    <div v-show="!listLoading" class="pagination-container">

      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                     :current-page.sync="listQuery.page" :page-sizes="[10,20,30, 50]" :page-size="listQuery.limit"
                     layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>
    <!--添加弹窗-->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form :model="form" :rules="rules" ref="form" label-width="100px">

        <el-form-item label="订单号" prop="multipleSelection">
          <el-input v-model="multipleSelection" placeholder="订单号"></el-input>
        </el-form-item>

        <el-form-item label="订单金额" prop="roleCode">
          <el-input v-model="form.roleCode" placeholder="订单金额"></el-input>
        </el-form-item>

        <el-form-item label="订单地址" prop="roleDesc">
          <el-input v-model="form.roleDesc" placeholder="订单地址"></el-input>
        </el-form-item>
        <el-form-item label="商品数量" prop="roleDept">
          <el-input v-model="form.roleDesc" placeholder="商品数量"></el-input>
        </el-form-item>
        <el-form-item label="订单日期" prop="roleDept">
          <el-input v-model="form.roleDesc" placeholder="订单日期"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel('form')">取 消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="create('form')">确 定</el-button>
        <el-button v-else type="primary" @click="update('form')">修 改</el-button>
      </div>
    </el-dialog>
    <!--分配弹窗-->
    <el-dialog :title="textMap[dialogDistributeStatus]" :visible.sync="dialogDistributeVisible">

      <el-form :model="distributeForm" :rules="distributeFormRules" ref="distributeForm" label-width="100px">
        <el-form-item label="分配订单数">
          <el-input v-model="multipleSelection.length" placeholder="分配订单数" :disabled="true"></el-input>
        </el-form-item>

        <el-form-item label="分配订单号" prop="ids">
          <el-input v-model="multipleSelection.toString()" placeholder="分配订单号" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="选择配送员" prop="distributeBy">
          <el-select v-model="distributeForm.distributeBy" placeholder="请选择" @focus="handleDept()" readonly>
            <el-option
              v-for="item in userList"
              :key="item.userId"
              :label="item.username"
              :value="item.username">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel('distributeForm')">取 消</el-button>
        <el-button v-if="dialogDistributeStatus=='distribute'" type="primary" @click="distribute('distributeForm')">
          确认分配
        </el-button>
      </div>
    </el-dialog>
    <!--收款弹窗-->
    <el-dialog :title="textMap[dialogGatheringStatus]" :visible.sync="dialogGatheringVisible">
      <el-form :model="distributeForm" :rules="distributeFormRules" ref="distributeForm" label-width="100px">
        <el-form-item label="收款订单数" prop="multipleSelection">
          <el-input v-model="multipleSelection.length" placeholder="收款订单数" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="收款订单号" prop="multipleSelection">
          <el-input v-model="multipleSelection.toString()" placeholder="收款订单号" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="roleDesc">
          <el-input v-model="form.roleDesc" placeholder="描述"></el-input>
        </el-form-item>
        <el-form-item label="选择配送员" prop="roleDept">

          <el-input v-model="form.deptName" placeholder="选择配送员" @focus="handleDept()" readonly></el-input>
          <el-input type="hidden" v-model="form.roleDeptId"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel('form')">取 消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="create('form')">确 定</el-button>
        <el-button v-else type="primary" @click="update('form')">修 改</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogDeptVisible">

      <el-tree class="filter-tree" :data="treeDeptData" :default-checked-keys="checkedKeys" check-strictly node-key="id"
               highlight-current ref="deptTree" @node-click="getNodeData" :props="defaultProps"
               :filter-node-method="filterNode" default-expand-all>
      </el-tree>
    </el-dialog>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogPermissionVisible">

      <el-tree class="filter-tree" :data="treeData" :default-checked-keys="checkedKeys" check-strictly node-key="id"
               highlight-current :props="defaultProps" show-checkbox ref="menuTree" :filter-node-method="filterNode"
               default-expand-all>
      </el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="updatePermession(roleId, roleCode)">更 新</el-button>
      </div>
    </el-dialog>
    <!--扫码枪录入-->
    <el-dialog :title="textMap[dialogScanerStatus]" :visible.sync="dialogScanerVisible">

      <el-form :model="scanerForm" :rules="scanerFormRules" ref="scanerForm" label-width="100px">
        <el-input
          type="textarea"
          :autosize="{ minRows: 2, maxRows: 4}"
          placeholder="请输入内容"
          v-model="scanerForm.str">
        </el-input>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel('scanerForm')">取 消</el-button>
        <el-button v-if="dialogScanerStatus=='scaner'" type="primary" @click="doScaner('scanerForm')">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    fetchList,
    getObj,
    addObj,
    putObj,
    delObj,
    permissionUpd,
    fetchRoleTree,
    fetchDeptTree
  } from "@/api/role";

  import {getOssToken, importStock, fetchOrderList} from "@/api/stock";
  import {fetchTree} from "@/api/menu";
  import {mapGetters} from "vuex";
  import {findByDept} from "@/api/user";
  import waves from "@/directive/waves/index.js"; // 水波纹指令
  import OSSUpload from "@/components/upload/OSSUpload";
  import OSS from 'ali-oss'

  const getOssStsToken = async (uri) => {

    let query = {url: "/"}
    const result = await getOssToken(query)
    console.log(result)
    const res = await result.data
    return res.data
  }

  const uploadOSS = async (fname, file, progress, uri) => {
    const token = await getOssStsToken(uri)
    const data = token.host.replace('http://', '').split('.')
    const client = new OSS.Wrapper({
      region: data[1],
      accessKeyId: token.accessid,
      accessKeySecret: token.signature,
      stsToken: token.policy,
      bucket: data[0],
    })

    const result = await client.multipartUpload(fname, file, {
      progress: progress
    })
    return fname
  }
  const addFile = async (url, file, imageList, uri) => {
    const imageItem = {
      src: '',
      percent: 0,
      isLoading: false,
      showDelete: false,
    }
    imageList.push(imageItem)
    //3.上传到阿里云图片服务器
    const progress = (percentage) => (callback) => {
      imageItem.percent = percentage * 100
      if (percentage === 1) {
        imageItem.showDelete = true
      }
      callback()
    }

    // 随机生成文件名
    function random_string(len) {
      len = len || 32
      const chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
      const maxPos = chars.length
      let pwd = ''
      for (let i = 0; i < len; i++) {
        pwd += chars.charAt(Math.floor(Math.random() * maxPos))
      }
      return pwd
    }

    const fname = random_string(6) + (new Date()).valueOf() + "." + file.name.split('.').pop();
    const result = await uploadOSS(fname, file, progress, uri)
    return fname
  }
  export default {
    name: "table_role",
    components: {OSSUpload},
    directives: {
      waves
    },
    data() {
      return {
        attachmentName: [],
        uri: [],
        imageList0: [],
        treeData: [],
        treeDeptData: [],
        checkedKeys: [],
        userList: [],
        multipleSelection: [],
        defaultProps: {
          children: "children",
          label: "name"
        },
        list: null,
        total: null,
        listLoading: true,
        listQuery: {
          page: 1,
          idsStr: undefined,
          limit: 20,
          orderStatus: undefined,
          username: undefined,
          ids: [],
          gmtOrderStart: undefined,
          gmtOrderEnd: undefined
        },
        form: {
          roleName: undefined,
          roleCode: undefined,
          roleDesc: undefined,
          deptName: undefined,
          roleDeptId: undefined
        },
        scanerForm: {
          str: undefined
        },
        createForm: {},
        distributeForm: {
          ids: [],
          distributeBy: undefined,
          orderAction: "DISTRIBUTE"
        },
        gatheringForm: {},
        roleId: undefined,
        roleCode: undefined,
        distributeFormRules: {},
        rules: {
          roleName: [
            {
              required: true,
              message: "角色名称",
              trigger: "blur"
            },
            {
              min: 3,
              max: 20,
              message: "长度在 3 到 20 个字符",
              trigger: "blur"
            }
          ],
          roleCode: [
            {
              required: true,
              message: "角色标识",
              trigger: "blur"
            },
            {
              min: 3,
              max: 20,
              message: "长度在 3 到 20 个字符",
              trigger: "blur"
            }
          ],
          roleDesc: [
            {
              required: true,
              message: "角色标识",
              trigger: "blur"
            },
            {
              min: 3,
              max: 20,
              message: "长度在 3 到 20 个字符",
              trigger: "blur"
            }
          ]
        },
        scanerFormRules: {},
        statusOptions: ["0", "1"],
        rolesOptions: undefined,
        dialogFormVisible: false,
        dialogDistributeVisible: false,
        dialogGatheringVisible: false,
        dialogDeptVisible: false,
        dialogPermissionVisible: false,
        dialogStatus: "",
        dialogScanerStatus: "",
        dialogScanerVisible: false,
        dialogDistributeStatus: "",
        dialogGatheringStatus: "",
        textMap: {
          update: "编辑",
          create: "创建",
          permission: "分配权限",

          distribute: "订单分配",
          gathering: "确认收款"
        },
        tableKey: 0,
        roleManager_btn_add: false,
        roleManager_btn_edit: false,
        roleManager_btn_del: false,

        roleManager_btn_perm: false,
        orderStatusOptions: [{
          value: 'WAIT_DISTRIBUTE',
          label: '待分配'
        }, {
          value: 'DISTRIBUTED',
          label: '已分配'
        }, {
          value: 'GATHERING_SUCCESS',
          label: '确认收款'
        }]
      };
    },
    created() {
      this.getList();
      this.roleManager_btn_add = this.permissions["sys_role_add"];
      this.roleManager_btn_edit = this.permissions["sys_role_edit"];
      this.roleManager_btn_del = this.permissions["sys_role_del"];
      this.roleManager_btn_perm = this.permissions["sys_role_perm"];
    },
    computed: {
      ...mapGetters(["elements", "permissions"])
    },
    methods: {
      toggleSelection(rows) {
        if (rows) {
          rows.forEach(row => {
            this.$refs.multipleTable.toggleRowSelection(row);
          });
        } else {
          this.$refs.multipleTable.clearSelection();
        }
      },
      handleSelectionChange(val) {

        this.multipleSelection = [];
        for (var i = 0; i < val.length; i++) {
          this.multipleSelection.push(val[0].orderId)
        }
      },
      addIdCard: async function (file) {
        const a = await addFile('/fcs-api/afterUpload', file, this.imageList0, this.uri[0],)

        const query = {"key": a}
        importStock(query).then(response => {
          alert(response)
        })
      },
      handleFilter() {
        this.listQuery.page = 1;
        this.getList();
      },
      getList() {
        this.listLoading = true;
        this.listQuery.ids=[]
        if(this.listQuery.idsStr&&this.listQuery.idsStr.length>0) {
          let arr = this.listQuery.idsStr.trim().split(',');
          if (arr.length > 0) {
            for (let i = 0; i < arr.length; i++) {
              this.listQuery.ids.push(arr[i].toString())
            }
          }
        }
        fetchOrderList(this.listQuery).then(response => {
          this.list = response.data.data.records;
          this.total = response.data.data.total;
          this.listLoading = false;
        });
      },
      handleSizeChange(val) {
        this.listQuery.limit = val;
        this.getList();
      },
      handleCurrentChange(val) {
        this.listQuery.page = val;
        this.getList();
      },
      handleCreate() {
        this.resetTemp();
        this.dialogStatus = "create";
        this.dialogFormVisible = true;
      },
      handleDistribute() {
        this.resetTemp();
        this.dialogDistributeStatus = "distribute";
        this.dialogDistributeVisible = true;
      },
      handleGathering() {
        this.resetTemp();
        this.dialogGatheringStatus = "gathering";
        this.dialogGatheringVisible = true;
      },
      handleScaner() {
        this.resetTemp();
        this.dialogScanerStatus = "scaner";
        this.dialogScanerVisible = true;
      },
      handleUpdate(row) {
        getObj(row.roleId).then(response => {
          this.form = response.data;
          this.form.deptName = row.deptName;
          this.form.roleDeptId = row.roleDeptId;
          this.dialogFormVisible = true;
          this.dialogStatus = "update";
        });
      },
      handlePermission(row) {
        fetchRoleTree(row.roleCode)
          .then(response => {
            this.checkedKeys = response.data;
            return fetchTree();
          })
          .then(response => {
            this.treeData = response.data;
            this.dialogStatus = "permission";
            this.dialogPermissionVisible = true;
            this.roleId = row.roleId;
            this.roleCode = row.roleCode;
          });
      },
      handleDept() {

        findByDept("配送部门").then(response => {
          this.userList = response.data.data;
        });
      },
      filterNode(value, data) {
        if (!value) return true;
        return data.label.indexOf(value) !== -1;
      },
      getNodeData(data) {
        this.dialogDeptVisible = false;
        this.form.roleDeptId = data.id;
        this.form.deptName = data.name;
        console.log(data);
      },
      handleDelete(row) {
        delObj(row.roleId).then(response => {
          this.dialogFormVisible = false;
          this.getList();
          this.$notify({
            title: "成功",
            message: "删除成功",
            type: "success",
            duration: 2000
          });
        });
      },
      create(formName) {
        const set = this.$refs;
        set[formName].validate(valid => {
          if (valid) {
            addObj(this.form).then(() => {
              this.dialogFormVisible = false;
              this.getList();
              this.$notify({
                title: "成功",
                message: "创建成功",
                type: "success",
                duration: 2000
              });
            });
          } else {
            return false;
          }
        });
      },
      distribute(formName) {
        const set = this.$refs;
        set[formName].validate(valid => {
          if (valid) {
            updateOrder(this.distributeForm).then(() => {
              this.dialogDistributeVisible = false;
              this.getList();
              this.$notify({
                title: "成功",
                message: "创建成功",
                type: "success",
                duration: 2000
              });
            });
          } else {
            return false;
          }
        });
      },
      doScaner(formName) {
        const set = this.$refs;
        set[formName].validate(valid => {
          if (valid) {
            this.listQuery.ids = []
            let arr = this.scanerForm.str.trim().split('\n');
            this.listQuery.idsStr=arr.toString()
            for (let i = 0;i<arr.length;i++)
            {
              this.listQuery.ids.push(arr[i].toString())
            }
            console.log(arr)
            this.getList();
            this.dialogScanerVisible = false;
            this.$notify({
              title: "成功",
              message: "创建成功",
              type: "success",
              duration: 2000
            });
      } else {
        return false;
  }
  })
  ;
  },
  cancel(formName)
  {
    this.dialogDistributeVisible = false;
    this.dialogScanerVisible = false;
    this.dialogGatheringVisible = false;
    this.dialogDeptVisible = false;
    this.dialogFormVisible = false;
    this.$refs[formName].resetFields();
  }
  ,
  update(formName)
  {
    const set = this.$refs;
    set[formName].validate(valid => {
      if (valid) {
        this.dialogFormVisible = false;
        putObj(this.form).then(() => {
          this.dialogFormVisible = false;
          this.getList();
          this.$notify({
            title: "成功",
            message: "修改成功",
            type: "success",
            duration: 2000
          });
        });
      } else {
        return false;
      }
    });
  }
  ,
  updatePermession(roleId, roleCode)
  {
    permissionUpd(roleId, this.$refs.menuTree.getCheckedKeys()).then(() => {
      this.dialogPermissionVisible = false;
      fetchTree()
        .then(response => {
          this.treeData = response.data;
          return fetchRoleTree(roleCode);
        })
        .then(response => {
          this.checkedKeys = response.data;
          this.$notify({
            title: "成功",
            message: "修改成功",
            type: "success",
            duration: 2000
          });
        });
    });
  }
  ,
  resetTemp()
  {
    this.form = {
      id: undefined,
      roleName: undefined,
      roleCode: undefined,
      roleDesc: undefined
    }
  }
  ,

  getToken()
  {
    const res = uploadOSS()

  }
  }
  }
  ;
</script>
